<?php

declare (strict_types=1);
/**
 * @copyright 深圳市易果网络科技有限公司
 * @version 1.0.0
 * @link https://dayiguo.com
 */

namespace App\Controller\user;

use App\Dao\UserAddrDao;
use App\Request\User\UserAddr\CreateRequest;
use App\Request\User\UserAddr\EditRequest;
use App\Middleware\User\UserMiddleware;

use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\AutoController;
use Hyperf\HttpServer\Annotation\Middleware;

/**
 * 用户地址控制器
 *
 * @AutoController()
 * @Middleware(UserMiddleware::class)
 * @author 谢声强(861167322@qq.com)
 * @package App\Controller\user
 */
class AddrController extends Controller
{
    /**
     * 用户地址 Dao
     *
     * @Inject
     * @var UserAddrDao
     */
    private $dao;

    /**
     * 用户地址列表
     */
    public function list()
    {
        $addr_list = $this->dao->list();

        $this->success($addr_list);
    }

    /**
     * 创建新地址
     *
     * @param CreateRequest $request
     */
    public function create(CreateRequest $request)
    {
        $params = $request->all();

        isset($params['is_default']) && $params['is_default'] = (int)$params['is_default'];

        $this->dao->create([
            'user_id' => uid(),
            'name' => $params['name'],
            'phone' => $params['phone'],
            'province' => $params['province'],
            'city' => $params['city'],
            'district' => $params['district'],
            'area_ids' => $params['area_ids'],
            'address' => $params['address'],
            'remark' => $params['remark'] ?? '',
            'is_default' => $params['is_default'] ?? 0
        ]);

        $this->success();
    }

    /**
     * 通过ID查询单条数据
     */
    public function getUserAddrById()
    {
        $id = (int)$this->request->input('id', 0);

        if ($id === 0) $this->error();

        $result = $this->dao->first($id);

        $result->makeHidden(['zip_code', 'created_at', 'updated_at', 'deleted_at']);

        $this->success( $result );
    }

    /**
     * 编辑地址
     *
     * @param EditRequest $request
     */
    public function edit(EditRequest $request)
    {
        $params = $request->all();

        $this->dao->update((int)$params['id'], [
            'name' => $params['name'],
            'phone' => $params['phone'],
            'province' => $params['province'],
            'city' => $params['city'],
            'district' => $params['district'],
            // 因为update其实是走的是Db，不会经过模型，所以要手动转成json格式。
            'area_ids' => $params['area_ids'],
            'address' => $params['address'],
            'remark' => $params['remark'] ?? '',
            'is_default' => (int)($params['is_default'] ?? 0),
        ]);

        $this->success();
    }

    /**
     * 删除地址
     */
    public function del()
    {
        $id = (int)$this->request->input('id', 0);

        if ($id === 0) $this->error();

        $this->dao->delete($id);

        $this->success();
    }
}